<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Library\Orders\Orders;
use App\Models\Currency;
use App\Models\Entrust;
use App\Models\Order;
use App\Models\Property;
use App\Models\User;
use App\Models\Message;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 委托单.
 */
class EntrustController extends Controller
{
    /**
     * 获取所有币种信息.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function currency_types(Request $request)
    {
        $data = Currency::where([
            'online_switch' => 1,
        ])->where('is_standard', '<>', 1)->orderBy('orderby')->select('id', 'name_en', 'logo')->get();

        foreach ($data as $val) {
            $val->logo = config('alioss.host') . '/' . $val->logo;
        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 交易单（买入卖出）.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function order_list(Request $request)
    {
        $data = [];
        $uid  = $request->get('uid'); //用户id
        $cid  = $request->get('cid'); //币种id
        $type = $request->get('type'); //类型 1买入 2卖出

        if (empty($uid) || empty($cid)) {
            return respF(1003);
        }
        //用户资产信息
        $porperty = Property::where(['cid' => $cid, 'uid' => $uid])
            ->select('balance', 'blocked')->first();
        //买5（价格从高到低）
        $buys = Order::where(['cid' => $cid, 'uid' => $uid, 'type' => 5])
            ->orderBy('price', 'desc')->limit(5)->select('price', 'num')->get();
        //卖5（价格从低到高）
        $sells = Order::where(['cid' => $cid, 'uid' => $uid, 'type' => 6])
            ->orderBy('price')->limit(5)->select('price', 'num')->get();

        $data['property'] = $porperty;
        $data['buys']     = $buys;
        $data['sells']    = $sells;

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 委托单列表.
     * 未成交包含部分成交 已撤销包含部分撤销
     *
     * @author hxq
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function entrust_list(Request $request)
    {
        $uid        = $request->get('uid'); //用户id
        //$cid        = $request->get('cid'); //币种id
        $start_date = $request->get('start_date') ?? date('Y-m-d', strtotime('-180 days')); //起始日期
        $end_date   = $request->get('end_date') ?? date('Y-m-d', time()); //结束日期
        //处理日期
        $start_date = $start_date . ' 00:00:00';
        $end_date   = $end_date . ' 23:59:59';
        //验证参数
        if (empty($uid)) {
            //缺少参数
            return respF(1000);
        }
        //验证uid
        $user = User::find($uid);
        if (!$user) {
            //用户不存在
            return respF(1001);
        }
        //验证币种ID
        /*if (!empty($cid)){
            $currency = Currency::find($cid);
            if (!$currency)
                return respF(1007);

            $where['cid']  = $cid;
        }*/
        $where['uid'] = $uid;
        //查询委托单
        $entrusts = Entrust::where($where)->whereIn('status', [1, 2, 3])
            ->where(function ($query) use ($start_date, $end_date) {
                $query->whereBetween('created_at', [$start_date, $end_date]);
            })
            ->orderBy('created_at', 'desc')->paginate(10);
        //没有数据
        if (!$entrusts) {
            return respF(1009);
        }
        //查询oba的币种ID
        $obaID = Currency::where('name_en', 'OBA')->value('id');
        //接收数组
        $list = [];
        //处理数据
        foreach ($entrusts as $k => $v) {
            /*if($cid){
                $list[$k]['curency_name'] = $currency->name_en;
                $list[$k]['cid']  = $cid;
            }else{
                $list[$k]['curency_name'] = $v->currency->name_en;
                $list[$k]['cid']  = $v->cid;
            }*/
            $list[$k]['currency_name'] = $v->currency->name_en;
            $list[$k]['cid']  = $v->cid;
            //币种小数点单位
            $list[$k]['unit'] = $v->currency->unit;
            //委托单ID
            $list[$k]['id'] = $v->id;
            //价格保留2位小数
            $list[$k]['price'] = number_format($v->price, 2,'.','');
            //oba显示整数，其他显示4位小数
            $list[$k]['num']  = number_format($v->num,$v->currency->unit,'.','');
            $list[$k]['deal'] = number_format($v->deal,$v->currency->unit,'.','');
            //转化状态
            $list[$k]['status'] = $v->status;
            if ($v->type == 3) {
                $list[$k]['type'] = 1;
            }
            if ($v->type == 4) {
                $list[$k]['type'] = 2;
            }
            //成交时间
            $list[$k]['created_at'] = strtotime($v->created_at);
            //没有成交时间
            /*if (empty($v->deal_time)) {
                //则显示创建时间
                $list[$k]['created_at'] = strtotime($v->created_at);
            }*/
            
        }
        if (collect($list)->count() == 0) {
            return respF(1009);
        }
        $data['list'] = $list;

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 取消委托
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/16
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function entrust_undo(Request $request)
    {
        $info = $request->all();
        if (empty($info['id'])) {
            return respF(1019);
        }
        $orders_model = new Orders();
        $re = $orders_model->cancel($info['id']);
        switch ($re['status']) {
            case 0:
                return respF(1006);
            case 1:
                $msg_model = new Message();
                //生成通知消息
                $msg = [
                    'msg_id' => 26,
                    'uid' => $re['uid'],
                    'message' => [
                        $re['number_no']
                    ],
                    "arr"=> ['number' => $info['id']]
                ];
                $msg_model->syspublishsmsAll($msg);
                return response()->json(['msg' => '操作成功', 'status' => 1]);
            case 2:
                return respF(1020);
        }
    }
}
